package com.xiehua.task.job.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.utils.json.Json;
import redis.clients.jedis.Jedis;

import java.util.UUID;

public class DelayJobPool implements JobPool<DelayJob> {

    private static final Logger logger = LoggerFactory.getLogger(DelayJobPool.class);

    public static final String JOB_POOL_DELAY_KEY = "task_job_pool_delay";

    private Jedis jedis;

    public DelayJobPool(Jedis jedis) {
        this.jedis = jedis;
    }

    /**
     * 添加一个job
     *
     * @param job
     * @return jobId
     */
    @Override
    public DelayJob push(DelayJob job) {
        job.setJobId(UUID.randomUUID().toString().replace("-", ""));
        if (jedis.hexists(JOB_POOL_DELAY_KEY, job.getJobId())) {
            logger.error("任务已经存在,请不要重复添加jobId:{}", job.getJobId());
            throw new RuntimeException("任务已经存在,请不要重复添加");
        }
        jedis.hset(JOB_POOL_DELAY_KEY, job.getJobId(), Json.toJson(job));
        return job;
    }

    /**
     * 删除一个job
     *
     * @param jobId
     */
    @Override
    public void del(String jobId) {
        if (jedis.hexists(JOB_POOL_DELAY_KEY, jobId)) jedis.hdel(JOB_POOL_DELAY_KEY, jobId);
    }

    /**
     * 判断是否包含一个job
     *
     * @param jobId
     * @return boolean
     */
    @Override
    public Boolean hasJob(String jobId) {
        return jedis.hexists(JOB_POOL_DELAY_KEY, jobId);
    }

    /**
     * 修改job
     *
     * @param job
     **/
    @Override
    public void updateJob(DelayJob job) {
        jedis.hset(JOB_POOL_DELAY_KEY, job.getJobId(), Json.toJson(job));
    }

    /**
     * 查询jobId 查询 job
     *
     * @param jobId
     **/
    @Override
    public DelayJob get(String jobId) {
        if (!hasJob(jobId)) return null;
        String str = jedis.hget(JOB_POOL_DELAY_KEY, jobId);
        return Json.toBean(str, DelayJob.class);
    }
}